package com.yoke.database.page;

import com.alibaba.druid.util.JdbcUtils;
import com.yoke.database.DatabaseContextHolder;
import com.yoke.system.log.LogType;
import com.yoke.system.log.SystemLog;
import com.yoke.util.StringUtil;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by jiangzeyin on 2017/5/18.
 */
public class SqlUtil {

    public static void doPage(Page page) throws SQLException {
        String[] sql = getSelectPageSql(page);
        DataSource dataSource = DatabaseContextHolder.getDataSource();
        SystemLog.LOG(LogType.SQL).info(sql[0]);
        List<Map<String, Object>> list = JdbcUtils.executeQuery(dataSource, sql[0]);
        if (list == null || list.size() < 1)
            return;
        Map<String, Object> count_map = list.get(0);
        if (count_map == null)
            return;
        long count = StringUtil.parseLong(count_map.get("count").toString());
        page.setTotalRecord(count);
        SystemLog.LOG(LogType.SQL).info(sql[1]);
        list = JdbcUtils.executeQuery(dataSource, sql[1]);
        page.setMapList(list);
    }

    public static String[] getSelectPageSql(Page page) {
        String[] countSql = new String[2];
        String sql = page.getSql();
        countSql[0] = getCountSql(sql.toString(), page);
        countSql[1] = getMysqlPageSql(page, new StringBuffer(sql));
        return countSql;
    }

    public static String getMysqlPageSql(Page page, StringBuffer sqlBuffer) {
        // 计算第一条记录的位置，Mysql中记录的位置是从0开始的。
        long offset = (page.getPageNo() - 1) * page.getPageSize();
        doWhere(sqlBuffer, page);
        // 判断是否需要排序
        if (page.getOrderBy() != null && !"".equals(page.getOrderBy())) {
            sqlBuffer.append(" order by " + page.getOrderBy());
        }
        sqlBuffer.append(" limit ").append(offset).append(",").append(page.getPageSize());
        return sqlBuffer.toString();
    }

    public static String getCountSql(String sql, Page page) {
        StringBuffer sqlBuffer = new StringBuffer(sql);
        doWhere(sqlBuffer, page);
        return "select count(1)  as count from (" + sqlBuffer + ") as total";
    }

    private static void doWhere(StringBuffer sqlBuffer, Page page) {
        if (!StringUtil.IsEmpty(page.getWhereWord())) {
            if (sqlBuffer.indexOf("where") == -1) {
                sqlBuffer.append(" where ");
            } else {
                sqlBuffer.append(" and ");
            }
            sqlBuffer.append(page.getWhereWord());
        }
    }
}
